package com.doule.farmerassistant.autoupdate;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;

import com.doule.farmerassistant.R;

/**
 * Created by Guohua on 2015/1/26.
 */
public class UpdateManager implements UpdateCheck.UpdateCheckListener {
    private static final String TAG = "UpdateManager";

    private UpdateInfo mUpdateInfo;

    private final String mUpdateUrl;
    private Context mContext;

    public UpdateManager(Context c, String updateUrl) {
        mContext = c;
        mUpdateUrl = updateUrl;
    }

    public void discard() {
        mContext = null;
    }

    public void startCheck() {
        UpdateCheck check = new UpdateCheck(mUpdateUrl, this);
        check.start();
    }

    @Override
    public void onUpdateCheckCompleted(UpdateInfo updateInfo) {
        if (updateInfo == null) {
            Log.e(TAG, "onUpdateCheckCompleted, updateInfo is null, not update");
            return;
        }

        mUpdateInfo = updateInfo;
        int currentVersionCode = ApkVersion.getCurrentApkVersionCode(mContext);
        if (currentVersionCode < updateInfo.getVersionCode()) {
            showUpdateNotify();
        } else {
            Log.e(TAG, "onUpdateCheckCompleted, current version code is not less than" +
                    " remote one, not update");
        }
    }

    private void showUpdateNotify() {
        if (mContext == null) {
            Log.e(TAG, "mContext is null, not show notify dialog");
            return;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setMessage(mUpdateInfo.getUpdateMessage());

        builder.setTitle(mContext.getString(R.string.update_dlg_title));

        builder.setPositiveButton(mContext.getString(R.string.update_dlg_confirm), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.e(TAG, "user confirm update");
                dialog.dismiss();
                startDownload();
            }
        });

        builder.setNegativeButton(mContext.getString(R.string.update_dlg_cancel), new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.e(TAG, "user cancel update");
                dialog.dismiss();
            }
        });

        builder.create().show();
    }

    private void startDownload() {
        if (mContext == null) {
            Log.e(TAG, "start download failed: mContext is null");
            return;
        }

        DownloadIntentService.startActionFoo(mContext, mUpdateInfo.getUrl(), "");
    }
}
